package server

import (
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

func SetRoute(engine *gin.Engine) {
	engine.Any("/hello", func(c *gin.Context) {
		r := c.Request
		fmt.Printf("url=%s uri=%s host=%s\n", r.URL, r.RequestURI, r.Host)
		
		c.JSON(200, gin.H {
			"message": "hello",
		})
	})

	engine.GET("/echo", func(c *gin.Context) {
		if (websocket.IsWebSocketUpgrade(c.Request)) {
			request := c.Request
			responseWriter := c.Writer
			conn, err := upgrader.Upgrade(responseWriter, request, responseWriter.Header())
			if err != nil {
				log.Println(err)
				c.AbortWithError(http.StatusInternalServerError, err)
				return
			}

			EchoHandler(conn)
		} else {
			c.JSON(http.StatusOK, gin.H {
				"message": "not supported",
			})
		}
	})

	engine.NoRoute(func(c *gin.Context) {
		c.Data(200, "text/plain", []byte("404 not found"));
	})
}

func EchoHandler(conn *websocket.Conn) {
	LOOP:
	for {
		messageType, data, err := conn.ReadMessage()
		if err != nil {
			log.Printf("err=%s, type=%d\n", err, messageType)
			break LOOP
		}
		switch messageType {
		case websocket.CloseMessage:
			fmt.Println("close conn")
			conn.Close()
			break LOOP

		case websocket.PingMessage:
			conn.WriteMessage(websocket.PongMessage, nil)

		case websocket.TextMessage:
			msg := string(data)
			reply := "from server:" + msg
			conn.WriteMessage(websocket.TextMessage, []byte(reply))
		}
	}
}